package deng.controller;

import deng.dto.UserPointsReq;
import deng.dto.UserRanking;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
public class UserRankingController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 往redis中存数据
    @PostMapping("/addUserPoint")
    public boolean addUserPoint(@RequestBody List<UserPointsReq> userPointsReqs){
        String key = "user:ranking";
        for (UserPointsReq userPointsReq : userPointsReqs) {
            String userId = userPointsReq.getUserId();
            //利用时间戳设置分数
            double score = userPointsReq.getPoints()+(1-(userPointsReq.getUpdateTime()/1e13));
            stringRedisTemplate.opsForZSet().add(key,userId,score);
        }
        return true;
    }

    //从redis中读取分数
    @GetMapping("/userRanking")
    public  List<UserRanking> userRanking(@RequestParam("num") int num){
        String key = "user:ranking";
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeWithScores(key, 0, num - 1);
        List<UserRanking> userRankings = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            UserRanking userRanking = new UserRanking();
            userRanking.setUserId(typedTuple.getValue());
            userRanking.setRedisScore(typedTuple.getScore());
            userRankings.add(userRanking);
        }
        return userRankings;
    }
}
